package com.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.book.bean.Book;
import com.book.bean.CarGood;
import com.book.biz.BookBiz;
import com.book.biz.impl.BookBizImpl;

public class AddCarGoodServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		
		int bid = Integer.parseInt(request.getParameter("bid"));
		BookBiz bookBiz = new BookBizImpl();
		Book book = bookBiz.getOneBook(bid);
		Map<Integer, CarGood> map = new HashMap<Integer, CarGood>();
		Object obj = session.getAttribute("map");
		if(obj!=null){
			map = (Map<Integer, CarGood>) obj;
		}
		if(map.containsKey(bid)){
			//有
			CarGood carGood = map.get(bid);
			carGood.setNum(carGood.getNum()+1);
		}else{
			//没有
			CarGood carGood = new CarGood(book,1);
			map.put(bid, carGood);
		}
		
		session.setAttribute("map", map);
		out.print("<script>alert('成功加入购物车');location='"+request.getContextPath()+"/SelectBook.do?type=all';</script>");
		
		
	}

}
